package com.example.mvp.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.example.mvp.bean.BaseBinderBean;
import com.example.mvp.binder.BaseDataBinder;
//import com.example.mvp.binder.BaseViewDataBinder;
//import com.example.mvp.delegate.VDelegate;
import com.example.mvp.delegate.XDelegate;

/**
 * LinearLayout基类
 * Created by sun.li on 2018/6/13.
 *
 * @author sun.li
 */

public abstract class BaseLinearLayout<T extends XDelegate> extends LinearLayout{

    /** 视图托管类对象*/
    protected T viewDelegate;

    /** 公共数据视图绑定控制器对象*/
    protected BaseDataBinder binder;

    protected Context mContext;

    public BaseLinearLayout(Context context) {
        super(context);
        this.mContext = context;
        createView();
    }

    public BaseLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        createView();
    }

    public BaseLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        createView();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        try {
            viewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    /**
     * 创建视图
     */
    public void createView(){
        if(null != viewDelegate){
            viewDelegate.create(LayoutInflater.from(mContext), null);
            if(null!=viewDelegate.getRootView()){
                this.addView(viewDelegate.getRootView());
                bindEvenListener();
            }
        }
    }

    /** 注册界面控件点击事件*/
    protected abstract void bindEvenListener();

    /** 指定界面的视图控制器，必须指定*/
    protected abstract Class<T> getDelegateClass();

    /** 公共数据视图绑定控制器数据对象*/
    public abstract BaseDataBinder getDataBinder();

    /** 根据数据刷新视图*/
    public <D extends BaseBinderBean> void notifyModelChanged(D data) {
        if (binder != null)
            binder.viewBindModel(viewDelegate, data);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(null != viewDelegate){
            this.removeAllViews();
        }
        viewDelegate = null;
        binder = null;
        mContext = null;
    }
}
